package com.lxd.kyvideo.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.lxd.kyvideo.common.ApiResult;
import com.lxd.kyvideo.config.SmsProperties;
import com.lxd.kyvideo.service.SmsService;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.exception.ClientException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private SmsProperties smsProperties;

    @Override
    public ApiResult sendSms(String phoneNumber,int code) throws ClientException {
        Pattern p = Pattern.compile("^1[1345789]\\d{9}$");
        Matcher m = p.matcher(phoneNumber);
        if(StrUtil.isBlank(phoneNumber)){
            return ApiResult.fail("请输入手机号码");
        }
        else if(! m.matches()){
            return ApiResult.fail("请输入正确的手机号码");
        }
        else {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(smsProperties.getAccessKeyId())
                    .accessKeySecret(smsProperties.getAccessKeySecret())
                    .build());


                    AsyncClient client = AsyncClient.builder()
                    .region("cn-hangzhou")
                            .credentialsProvider(provider)
                            .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com")).build();
                    SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName(smsProperties.getSignName())
                    .templateCode(smsProperties.getTemplateCode())
                    .phoneNumbers(phoneNumber)
                    .templateParam("{\"code\":\""+code+"\"}")
                    .build();
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = null;
            try {
                resp = response.get();
                if(resp.getBody().getCode().equals("OK")) {
                    return ApiResult.ok(resp.getBody(),"验证码已发送，请查收短信");
                }
                else {
                    return ApiResult.fail("发送短信验证失败");
                }
            }
            catch (Exception ex){
                return ApiResult.fail("发送短信验证码异常，错误消息" +ex.getMessage());
            }finally {
                if(client != null) {
                    client.close();
                }
            }
        }
    }
}
